package com.uzai.console.service.sop.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.taobao.api.internal.toplink.embedded.websocket.util.StringUtil;
import com.uzai.common.entity.User;
import com.uzai.common.entity.WechatUser;
import com.uzai.common.entity.WxworkUser;
import com.uzai.common.enums.*;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.msg.MsgDto;
import com.uzai.common.msg.NoticeMsgDto;
import com.uzai.common.result.ResponseCode;
import com.uzai.common.utils.EsIndexName;
import com.uzai.console.common.ResponseMsg;
import com.uzai.console.common.UzaiRespVo;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.constant.ES.ElasticsearchUtil;
import com.uzai.console.dto.feign.redpacket.RedPacketSendByIdDto;
import com.uzai.console.dto.rocketmq.wxgroup.AddFriendReqDto;
import com.uzai.console.dto.sop.soptaskaddinfo.SopTaskAddInfoIdDto;
import com.uzai.console.dto.sop.soptaskaddinfo.SopTaskAddInfoIdListDto;
import com.uzai.console.dto.sop.soptaskaddinfo.SopTaskAddInfoQuery;
import com.uzai.console.entity.*;
import com.uzai.console.entity.es.WxqBlacklistPrv;
import com.uzai.console.entity.es.WxqBlacklistPub;
import com.uzai.console.entity.es.WxqWorkBlacklistPrv;
import com.uzai.console.entity.es.WxqWorkBlacklistPub;
import com.uzai.console.enums.SopTaskStatusEnum;
import com.uzai.console.mapper.*;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.feign.RedPacketFeignService;
import com.uzai.console.service.rocketmq.NoticeMsgPushProducerService;
import com.uzai.console.service.sop.SopTaskAddInfoService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.sop.soptaskaddinfo.SopTaskAddInfoVo;
import org.checkerframework.checker.units.qual.A;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 自动SOP任务发送明细
 * @author liuqi
 * @date 2021年08月13日 11:34
 */
@Service
public class SopTaskAddInfoServiceImpl implements SopTaskAddInfoService {

    Logger logger = LoggerFactory.getLogger(SopTaskAddInfoServiceImpl.class);

    @Autowired
    private ZombieFanTaskMapper zombieFanTaskMapper;
    @Autowired
    private SopTaskAddInfoMapper sopTaskAddInfoMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private SopTaskMapper sopTaskMapper;
    @Autowired
    private ElasticsearchUtil elasticsearchUtil;
    @Autowired
    private NoticeMsgPushProducerService noticeMsgPushProducerService;
    @Autowired
    private WechatUserMapper wechatUserMapper;
    @Autowired
    private WxworkUserMapper wxworkUserMapper;
    @Autowired
    private RedPacketFeignService redPacketFeignService;
    @Autowired
    private RedPacketMapper redPacketMapper;
    @Autowired
    private UserService userService;

    /**
     * 查询清理僵尸粉任务列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskAddInfoQuery
     * @return null
     */
    public Page<SopTaskAddInfoVo> findSopTaskAddInfoList(SopTaskAddInfoQuery sopTaskAddInfoQuery){

        Integer now = DateUtil.getNowTime();

        //新建返回到页面的LIST对象
        List<SopTaskAddInfoVo> sopTaskAddInfoVoList = new ArrayList<>();

        //执行分页查询对象
        Page<SopTaskAddInfo> page = new Page<>();
        sopTaskAddInfoQuery.convert(page);
        List<SopTaskAddInfo> sopTaskAddInfoList = sopTaskAddInfoMapper.findByList(page, sopTaskAddInfoQuery);
        if(sopTaskAddInfoList != null){
            for (SopTaskAddInfo sopTaskAddInfo : sopTaskAddInfoList){
                SopTaskAddInfoVo sopTaskAddInfoVo = new SopTaskAddInfoVo();
                BeanUtils.copyProperties(sopTaskAddInfo, sopTaskAddInfoVo);

                //查询群发类型名称
                if(org.apache.commons.lang3.StringUtils.isNotBlank(sopTaskAddInfo.getDeviceType())){
                    DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(sopTaskAddInfo.getDeviceType());
                    if(deviceTypeEnum != null){
                        sopTaskAddInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
                    }
                }

                //机器人信息
                if(sopTaskAddInfo.getDeviceUniqueId() != null){
                    Device device = deviceService.findDeviceInfoByDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId(), sopTaskAddInfo.getDeviceType(), sopTaskAddInfo.getMerId());
                    if(device != null){
                        sopTaskAddInfoVo.setDeviceId(device.getDeviceId());
                        sopTaskAddInfoVo.setDeviceName(device.getDeviceName());
                        sopTaskAddInfoVo.setDeviceRemark(device.getDeviceRemark());
                    }
                }

                if(StringUtils.isNotBlank(sopTaskAddInfo.getWxid())){
                    User user = userService.findUserInfoByWxid(sopTaskAddInfo.getMerId(),sopTaskAddInfo.getWxid(),sopTaskAddInfo.getDeviceType());
                    if(user != null){
                        sopTaskAddInfoVo.setUserId(user.getId());
                    }
                }

                sopTaskAddInfoVoList.add(sopTaskAddInfoVo);

            }
        }
        //返回到页面分页对象
        Page<SopTaskAddInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(sopTaskAddInfoVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 查询添加好友任务明细详情
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskAddInfoIdDto
     * @return null
     */
    public SopTaskAddInfoVo findSopTaskAddInfo(SopTaskAddInfoIdDto sopTaskAddInfoIdDto){
        //返回到页面的VO对象
        SopTaskAddInfoVo sopTaskAddInfoVo = new SopTaskAddInfoVo();

        if(sopTaskAddInfoIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, ResponseMsg.PARAM_ERROR);
        }

        SopTaskAddInfo sopTaskAddInfo = sopTaskAddInfoMapper.selectById(sopTaskAddInfoIdDto.getId(), sopTaskAddInfoIdDto.getMerId());

        if(sopTaskAddInfo == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该记录不存在");
        }

        //将查询到的数据复制到页面VO中
        BeanUtils.copyProperties(sopTaskAddInfo, sopTaskAddInfoVo);

        //查询群发类型名称
        if(org.apache.commons.lang3.StringUtils.isNotBlank(sopTaskAddInfo.getDeviceType())){
            DeviceTypeEnum deviceTypeEnum = DeviceTypeEnum.getByKey(sopTaskAddInfo.getDeviceType());
            if(deviceTypeEnum != null){
                sopTaskAddInfoVo.setDeviceTypeName(deviceTypeEnum.getRemark());
            }
        }

        //机器人信息
        if(sopTaskAddInfo.getDeviceUniqueId() != null){
            Device device = deviceService.findDeviceInfoByDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId(), sopTaskAddInfo.getDeviceType(), sopTaskAddInfo.getMerId());
            sopTaskAddInfoVo.setDeviceId(device.getDeviceId());
            sopTaskAddInfoVo.setDeviceName(device.getDeviceName());
            sopTaskAddInfoVo.setDeviceRemark(device.getDeviceRemark());
        }

        return  sopTaskAddInfoVo;
    }

    /**
     * 批量处理清理僵尸粉任务
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTaskAddInfoIdListDto
     * @return null
     */
    public void batchDeleteSopTaskAddInfo(SopTaskAddInfoIdListDto sopTaskAddInfoIdListDto){
        List<Long> idList = sopTaskAddInfoIdListDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择记录");
        }

        if(sopTaskAddInfoIdListDto.getTaskId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请选择主任务id");
        }

        SopTask sopTask = sopTaskMapper.selectById(sopTaskAddInfoIdListDto.getTaskId(), sopTaskAddInfoIdListDto.getMerId());
        if(sopTask == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "主任务不存在");
        }

        for (Long id : idList) {
            //删除添加明细
            sopTaskAddInfoMapper.deleteById(id, sopTaskAddInfoIdListDto.getMerId());
        }
    }

    /**
     * 自动SOP添加明细请求
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param sopTask
     * @return null
     */
    //@Transactional
    public void autoSendSopTaskAddInfo(SopTask sopTask){
        if(sopTask == null){
            return;
        }

        //获取该任务的免骚扰时间(以小时为单位)
        Integer busyTimeInterval = Tools.getInteger(sopTask.getBusyTimeInterval());
        int now = DateUtil.getNowTime();

        //根据机器人分组查询每组内该关联的最小id的发送明细
        List<SopTaskAddInfo> sopTaskAddInfoList = sopTaskAddInfoMapper.selectMinIdByTaskId(sopTask.getId(), sopTask.getMerId());
        if(sopTaskAddInfoList != null && sopTaskAddInfoList.size() > 0){
            for (SopTaskAddInfo sopTaskAddInfo : sopTaskAddInfoList) {

                logger.info("-查询SOP任务明细-sopTaskAddInfo={}",JSONObject.toJSONString(sopTaskAddInfo));

                //删除添加明细记录
                sopTaskAddInfoMapper.deleteById(sopTaskAddInfo.getId(), sopTaskAddInfo.getMerId());

                try {
                    if(StringUtils.isNotBlank(sopTaskAddInfo.getDeviceType())){
                        Device device = deviceService.findDeviceInfoByDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId(), sopTaskAddInfo.getDeviceType(), sopTaskAddInfo.getMerId());
                        if(device != null){
                            //查券未下单或者未下单
                            if(sopTask.getType().intValue() == 1 || sopTask.getType().intValue() == 2){
                                //个人微信会员
                                if(sopTaskAddInfo.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {
                                    WechatUser wechatUser = wechatUserMapper.selectById(sopTaskAddInfo.getDataId(), sopTaskAddInfo.getMerId());
                                    if (wechatUser != null) {
                                        //判断会员最后群发时间
                                        if(now-busyTimeInterval*3600 > Tools.getInteger(wechatUser.getLastGroupSendTime())){
                                            //发送消息
                                            String msg = Tools.getStr(sopTask.getMsg());
                                            if(StringUtils.isNotBlank(msg)){
                                                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                                                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                                                msgDto.setContent(noticeMsgDto);
                                                msgDto.setId(IdWorker.getId());
                                                msgDto.setDeviceType(device.getRecvmsgType());
                                                msgDto.setDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId());
                                                msgDto.setMerId(sopTaskAddInfo.getMerId());
                                                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                                                //替换变量
                                                msg = msg.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()));
                                                noticeMsgDto.setContent(msg);
                                                noticeMsgDto.setBizUserId(sopTaskAddInfo.getWxid());
                                                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                                                noticeMsgDto.setGroupId(null);
                                                noticeMsgDto.setNickName(sopTaskAddInfo.getNick());
                                                noticeMsgDto.setMsgSource(1);
                                                noticeMsgDto.setDelay(0);
                                                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                                                noticeMsgPushProducerService.sendMessage(msgDto);
                                            }

                                            String remark = Tools.getStr(sopTask.getRemark());
                                            if (StringUtils.isNotBlank(remark)) {
                                                remark = remark.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()))
                                                        .replace("[备注时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                                wechatUser.setRemark(remark);
                                            }

                                            if (StringUtils.isNotBlank(sopTask.getUserTags())) {
                                                wechatUser.setSysTags(sopTask.getUserTags());
                                            }

                                            if (StringUtils.isNotBlank(sopTask.getTags())) {
                                                wechatUser.setTags(sopTask.getTags());
                                            }
                                            //修改最后群发时间
                                            wechatUser.setLastGroupSendTime(now);
                                            wechatUserMapper.updateRemarkAndTags(wechatUser);

                                        }
                                    }
                                }else if (sopTaskAddInfo.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())){//企业微信会员
                                    WxworkUser wxworkUser = wxworkUserMapper.selectById(sopTaskAddInfo.getDataId(), sopTaskAddInfo.getMerId());
                                    if (wxworkUser != null) {
                                        //判断会员最后群发时间
                                        if(now-busyTimeInterval*3600 > Tools.getInteger(wxworkUser.getLastGroupSendTime())){
                                            //发送消息
                                            String msg = Tools.getStr(sopTask.getMsg());
                                            if(StringUtils.isNotBlank(msg)){
                                                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                                                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                                                msgDto.setContent(noticeMsgDto);
                                                msgDto.setId(IdWorker.getId());
                                                msgDto.setDeviceType(device.getRecvmsgType());
                                                msgDto.setDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId());
                                                msgDto.setMerId(sopTaskAddInfo.getMerId());
                                                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                                                //替换变量
                                                msg = msg.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()));
                                                noticeMsgDto.setContent(msg);
                                                noticeMsgDto.setBizUserId(sopTaskAddInfo.getWxid());
                                                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                                                noticeMsgDto.setGroupId(null);
                                                noticeMsgDto.setNickName(sopTaskAddInfo.getNick());
                                                noticeMsgDto.setMsgSource(1);
                                                noticeMsgDto.setDelay(0);
                                                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                                                noticeMsgPushProducerService.sendMessage(msgDto);
                                            }

                                            String remark = Tools.getStr(sopTask.getRemark());
                                            if (StringUtils.isNotBlank(remark)) {
                                                remark = remark.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()))
                                                        .replace("[备注时间]", Tools.getDateFormat(new Date(), "yyMMdd"));
                                                wxworkUser.setRemark(remark);
                                            }

                                            if (StringUtils.isNotBlank(sopTask.getUserTags())) {
                                                wxworkUser.setSysTags(sopTask.getUserTags());
                                            }

                                            if (StringUtils.isNotBlank(sopTask.getTags())) {
                                                wxworkUser.setTags(sopTask.getTags());
                                            }

                                            //修改最后群发时间
                                            wxworkUser.setLastGroupSendTime(now);

                                            wxworkUserMapper.updateRemarkAndTags(wxworkUser);

                                        }
                                    }
                                }
                            }else if(sopTask.getType().intValue() == 3) { //红包未领取
                                //是否重复发送红包卡片
                                RedPacket redPacket = redPacketMapper.selectById(sopTaskAddInfo.getDataId(), sopTaskAddInfo.getMerId());
                                //此红包还未被领取
                                if(redPacket != null && redPacket.getStatus().intValue() == RedPackStatusEnum.UNCLAIMED_VALUE){
                                    //个人微信会员
                                    if(redPacket.getDeviceType().equals(DeviceTypeEnum.DT_PC_WECHAT.getKey())) {
                                        WechatUser wechatUser = wechatUserMapper.selectById(redPacket.getUserId(), sopTaskAddInfo.getMerId());
                                        if (wechatUser != null) {
                                            //判断会员最后群发时间
                                            if (now - busyTimeInterval * 3600 > Tools.getInteger(wechatUser.getLastGroupSendTime())) {

                                                if (Tools.getInteger(sopTask.getResend()).intValue() == 1) {
                                                    //根据红包id发送红包卡片
                                                    RedPacketSendByIdDto redPacketSendByIdDto = new RedPacketSendByIdDto();
                                                    redPacketSendByIdDto.setId(sopTaskAddInfo.getDataId());
                                                    UzaiRespVo<Boolean> uzaiRespVo = redPacketFeignService.sendRedpacketById(redPacketSendByIdDto);
                                                    logger.info("--SOP任务发送红包卡片--para={}, result={}", JSONObject.toJSONString(redPacketSendByIdDto), JSONObject.toJSONString(uzaiRespVo));
                                                }

                                                //发送消息
                                                String msg = Tools.getStr(sopTask.getMsg());
                                                if (StringUtils.isNotBlank(msg)) {
                                                    MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                                                    NoticeMsgDto noticeMsgDto = new NoticeMsgDto();
                                                    msgDto.setContent(noticeMsgDto);
                                                    msgDto.setId(IdWorker.getId());
                                                    msgDto.setDeviceType(device.getRecvmsgType());
                                                    msgDto.setDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId());
                                                    msgDto.setMerId(sopTaskAddInfo.getMerId());
                                                    msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                                                    //替换变量
                                                    msg = msg.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()));
                                                    noticeMsgDto.setContent(msg);
                                                    noticeMsgDto.setBizUserId(sopTaskAddInfo.getWxid());
                                                    noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                                                    noticeMsgDto.setGroupId(null);
                                                    noticeMsgDto.setNickName(sopTaskAddInfo.getNick());
                                                    noticeMsgDto.setMsgSource(1);
                                                    noticeMsgDto.setDelay(0);
                                                    noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                                                    noticeMsgPushProducerService.sendMessage(msgDto);
                                                }

                                                wechatUser.setLastGroupSendTime(now);
                                                wechatUserMapper.updateRemarkAndTags(wechatUser);
                                            }
                                        }
                                    }
                                }else if (sopTaskAddInfo.getDeviceType().equals(DeviceTypeEnum.DT_WORK_WECHAT.getKey())) {//企业微信会员
                                    WxworkUser wxworkUser = wxworkUserMapper.selectById(redPacket.getUserId(), sopTaskAddInfo.getMerId());
                                    if (wxworkUser != null) {
                                        //判断会员最后群发时间
                                        if (now - busyTimeInterval * 3600 > Tools.getInteger(wxworkUser.getLastGroupSendTime())) {
                                            if(Tools.getInteger(sopTask.getResend()).intValue() == 1){
                                                //根据红包id发送红包卡片
                                                RedPacketSendByIdDto redPacketSendByIdDto = new RedPacketSendByIdDto();
                                                redPacketSendByIdDto.setId(sopTaskAddInfo.getDataId());
                                                UzaiRespVo<Boolean> uzaiRespVo = redPacketFeignService.sendRedpacketById(redPacketSendByIdDto);
                                                logger.info("--SOP任务发送红包卡片--para={}, result={}", JSONObject.toJSONString(redPacketSendByIdDto), JSONObject.toJSONString(uzaiRespVo));
                                            }

                                            //发送消息
                                            String msg = Tools.getStr(sopTask.getMsg());
                                            if(StringUtils.isNotBlank(msg)){
                                                MsgDto<NoticeMsgDto> msgDto = new MsgDto<>();
                                                NoticeMsgDto  noticeMsgDto = new NoticeMsgDto();
                                                msgDto.setContent(noticeMsgDto);
                                                msgDto.setId(IdWorker.getId());
                                                msgDto.setDeviceType(device.getRecvmsgType());
                                                msgDto.setDeviceUniqueId(sopTaskAddInfo.getDeviceUniqueId());
                                                msgDto.setMerId(sopTaskAddInfo.getMerId());
                                                msgDto.setMsgType(MessageFuncEnum.SEND_CHAT_MESSAGE.getValue());
                                                //替换变量
                                                msg = msg.replace("[昵称]", Tools.getStr(sopTaskAddInfo.getNick()));
                                                noticeMsgDto.setContent(msg);
                                                noticeMsgDto.setBizUserId(sopTaskAddInfo.getWxid());
                                                noticeMsgDto.setContentType(MessageTypeEnum.MT_TEXT.getValue());
                                                noticeMsgDto.setGroupId(null);
                                                noticeMsgDto.setNickName(sopTaskAddInfo.getNick());
                                                noticeMsgDto.setMsgSource(1);
                                                noticeMsgDto.setDelay(0);
                                                noticeMsgDto.setMsgBizType(KefuSendMsgEnum.UNSOLICITEDMSG.getKey());
                                                noticeMsgPushProducerService.sendMessage(msgDto);
                                            }

                                            wxworkUser.setLastGroupSendTime(now);
                                            wxworkUserMapper.updateRemarkAndTags(wxworkUser);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }catch (Exception e){
                    logger.error("处理SOP任务明细失败");
                }
            }
            sopTaskMapper.updateById(sopTask);
        }else{//添加完成，则需要修改任务为已完成
            sopTask.setStatus(SopTaskStatusEnum.COMPLETED.getId());
            sopTaskMapper.updateById(sopTask);
        }
    }

}
